package com.zhou.base.resilience4j.test.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhou.base.resilience4j.test.entity.SystemLog;
import com.zhou.base.resilience4j.test.exception.BusinessAException;
import com.zhou.base.resilience4j.test.exception.BusinessBException;
import com.zhou.base.resilience4j.test.mapper.SystemLogMapper;
import com.zhou.base.resilience4j.test.service.ISystemLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 * 系统日志表 服务实现类
 * </p>
 *
 * @author zcy
 * @since 2022-08-12
 */
@Slf4j
@Service
public class SystemLogServiceImpl extends ServiceImpl<SystemLogMapper, SystemLog> implements ISystemLogService {

    private AtomicInteger count=new AtomicInteger();

    @Override
    public List<SystemLog> queryAll(){
        int num = count.getAndIncrement();
        log.info("count的值 = " + num);
        if (num % 4 == 1){
            throw new BusinessAException("异常A，不需要被记录");
        }
        if (num % 4 == 2 || num % 4 == 3){
            throw new BusinessBException("异常B，需要被记录");
        }
        log.info("服务正常运行，获取用户列表");
        // 模拟数据库的正常查询
        return list();

    }

    @Override
    public List<SystemLog> queryAllTestTimeLimiter() throws InterruptedException {
        int num = count.getAndIncrement();
        log.info("count的值 = " + num);
        if (num % 4 == 1){
            throw new BusinessAException("异常A，不需要被记录");
        }
        if (num % 4 == 2){
            throw new BusinessBException("异常B，需要被记录");
        }
        if (num % 4 == 3){
            Thread.sleep(5000);
        }
        log.info("服务正常运行，获取用户列表");
        // 模拟数据库的正常查询
        return list();
    }

    @Override
    public List<SystemLog> queryAllWithRateLimiter() throws InterruptedException  {
        int num = count.getAndIncrement();
        log.info("count的值 = " + num);
        Thread.sleep(5000);
        log.info("服务正常运行，获取用户列表");
        // 模拟数据库正常查询
        return list();
    }

    @Override
    public List<SystemLog> processWithBulkhead() throws InterruptedException {
        int num = count.getAndIncrement();
        log.info("count的值 = " + num);
        log.info("服务正常运行，获取用户列表");
        Thread.sleep(1000);
        return list();
    }

    @Override
    public List<SystemLog> processWithRetry() {
        int num = count.getAndIncrement();
        log.info("count的值 = " + num);
        if (num % 4 == 1){
            throw new BusinessAException("异常A，需要重试");
        }
        if (num % 4 == 2){
            return null;
        }
        if (num % 4 == 3){
            throw new BusinessBException("异常B，需要重试");
        }
        log.info("服务正常运行，获取用户列表");
        return list();
    }
}
